//
//  RoseLoginViewController.m
//  ROSE
//
//  Created by 艾阳 on 2018/5/28.
//  Copyright © 2018年 HeNanZhongDunYunAn. All rights reserved.
//

#import "RoseLoginViewController.h"
#import "NSArray+HJImages.h"
#import "ZSRegisterVC.h"
#import "ZSForgetPwdVC.h"
#import "AiNavigationViewController.h"


@interface RoseLoginViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UIView *middleLine;
@property (nonatomic, strong) UIImageView *logoImageView;
@end

static const CGFloat kMaxW = 280.f;
static const CGFloat kMarginY10 = 10.f;
static const CGFloat kMarginY20 = 20.f;
static const CGFloat kBtnH = 40.f;

static const CGFloat kTextFieldH = 30.f;
static const CGFloat kLoginFontSize = 16.f;
static const CGFloat kOtherFontSize = 14.f;
static const CGFloat kTFLeftW = 30.f;
static const CGFloat kTFLeftH = 20.f;

@implementation RoseLoginViewController
#pragma mark - Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self hideKeyboard];
}

- (void)dealloc{
    
    [self.bgImageView stopAnimating];
}
#pragma mark - About UI
- (void)setupUI{
    
    /** 设置self.view */
    self.view.backgroundColor = [UIColor themeColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    
    /** 设置背景 */
//    self.bgImageView.animationImages = [NSArray hj_imagesWithLocalGif:@"login_bg_gif_01" expectSize:self.view.bounds.size];
//    [self.bgImageView startAnimating];
    [self.bgImageView setImage:[UIImage imageNamed:@"login-bg2"]];
    self.bgImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:self.bgImageView];
    
    /** 设置内容视图 */
    self.containerView.backgroundColor = [UIColor clearColor];
    [self.bgImageView addSubview:self.containerView];
    
    /** 设置logo */
    self.logoImageView = [[UIImageView alloc] init];
    self.logoImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.logoImageView setImage:[UIImage imageNamed:@"logoBack"]];
    [self.containerView addSubview:self.logoImageView];
    
    /** 设置账号输入 */
    self.accountTF.placeholder = @"请输入你的账号";
    self.accountTF.tintColor = [UIColor whiteColor];
    self.accountTF.textColor = [UIColor whiteColor];
    self.accountTF.font = [UIFont systemFontOfSize:kOtherFontSize];
    self.accountTF.leftViewMode = UITextFieldViewModeAlways;
    self.accountTF.delegate = self;
    [self.accountTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
//    UIImageView *accountImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, kTFLeftW, kTFLeftH)];
//    accountImageV.contentMode = UIViewContentModeLeft;
//    accountImageV.image = [UIImage imageNamed:@"login_account"];
//    self.accountTF.leftView = accountImageV;
    CGRect frame = self.accountTF.frame;
    frame.size.width = 8;// 距离左侧的距离
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    self.accountTF.leftViewMode = UITextFieldViewModeAlways;
    self.accountTF.leftView = leftview;
    self.accountTF.layer.borderWidth = 1.0f;
    self.accountTF.layer.cornerRadius = 15.0f;
    self.accountTF.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.containerView addSubview:self.accountTF];
    
    /** 设置密码输入 */
    //    UIImageView *passwordImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kTFLeftW, kTFLeftH)];
    //    passwordImageV.contentMode = UIViewContentModeLeft;
    //    passwordImageV.image = [UIImage imageNamed:@"login_password"];
    //    self.passwordTF.leftViewMode = UITextFieldViewModeAlways;
    //    self.passwordTF.leftView = passwordImageV;
    frame.size.width = 8;// 距离左侧的距离
    UIView *leftview1 = [[UIView alloc] initWithFrame:frame];
    self.passwordTF.leftViewMode = UITextFieldViewModeAlways;
    self.passwordTF.leftView = leftview1;
    self.passwordTF.tintColor = [UIColor whiteColor];
    self.passwordTF.textColor = [UIColor whiteColor];
    self.passwordTF.font = [UIFont systemFontOfSize:kOtherFontSize];
    self.passwordTF.placeholder = @"请输入你的密码";
    self.passwordTF.delegate = self;
    self.passwordTF.secureTextEntry = YES;
    [self.passwordTF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.passwordTF.layer.borderWidth = 1.0f;
    self.passwordTF.layer.cornerRadius = 15.0f;
    self.passwordTF.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.containerView addSubview:self.passwordTF];
    self.passwordTF.text=@"111111";
    self.accountTF.text = @"13838031205";
    /** 设置登录按钮 */
    self.loginBtn.layer.cornerRadius = 15.f;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.borderWidth = 1.f;
    self.loginBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:kLoginFontSize];
    [self.loginBtn addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginBtn setTitle:@"立 即 登 录" forState:UIControlStateNormal];
    [self.loginBtn.titleLabel setFont:[UIFont systemFontOfSize:16.0 weight:6.f]];
    self.loginBtn.backgroundColor = [UIColor whiteColor];
    [self.loginBtn setTitleColor:[UIColor themeColor] forState:(UIControlStateNormal)];
    [self.loginBtn setTitle:@"登录中..." forState:(UIControlStateDisabled)];
    [self.containerView addSubview:self.loginBtn];
    
    /** 设置注册按钮 */
    self.registBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.registBtn.titleLabel.font = [UIFont systemFontOfSize:kOtherFontSize];
    [self.registBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    [self.registBtn addTarget:self action:@selector(registAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerView addSubview:self.registBtn];
    self.registBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentRight;
    
    /** 设置重置密码按钮 */
    self.resetPasswordBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.resetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:kOtherFontSize];
    [self.resetPasswordBtn addTarget:self action:@selector(resetPasswordAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.resetPasswordBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [self.containerView addSubview:self.resetPasswordBtn];
    self.resetPasswordBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    
    /** 设置注册和忘记密码中间的线*/
    self.middleLine = [ [UIView alloc]init];
    self.middleLine.backgroundColor = [UIColor whiteColor];
    [self.containerView addSubview:self.middleLine];
    
    /** 布局 */
    [self make_layout];
}


- (void)make_layout{
    
    [self.bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [self.passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kMaxW);
        make.height.mas_equalTo(kTextFieldH);
        make.center.mas_equalTo(self.containerView);
        
    }];
    
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kMaxW);
        make.height.mas_equalTo(kTextFieldH);
        make.centerX.mas_equalTo(self.containerView);
        make.bottom.mas_equalTo(self.passwordTF.mas_top).with.offset(-kMarginY20);
    }];
    
    
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kMaxW);
        make.height.mas_equalTo(kTextFieldH);
        make.centerX.mas_equalTo(self.containerView);
        make.top.mas_equalTo(self.passwordTF.mas_bottom).with.offset(kMarginY20);
    }];
    
    // logo 
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kMaxW);
        make.height.mas_equalTo(41.5f);
        make.centerX.mas_equalTo(self.containerView);
        make.bottom.mas_equalTo(self.accountTF.mas_top).with.offset(-60);
    }];
    
    [self.registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(size_width/2.f-82.0f);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).with.offset(kMarginY10);
        make.height.mas_equalTo(kBtnH);
        make.width.mas_equalTo(80.f);
    }];
    
    
    [self.resetPasswordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(size_width/2.f+2.f);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).with.offset(kMarginY10);
        make.height.mas_equalTo(kBtnH);
        make.width.mas_equalTo(80.f);
    }];
    
    [self.middleLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(size_width/2.f-0.5f);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).with.offset(kMarginY10+12);
        make.width.mas_equalTo(.5f);
        make.height.mas_equalTo(kBtnH-24);
    }];
    
}




#pragma mark - Pravite Method
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


#pragma mark - Event response
- (void)tapAction{
    
    [self hideKeyboard];
}


/**
 登录
 */
- (void)loginAction:(UIButton *)sender{
    
    [self hideKeyboard];
    NSString *account = self.accountTF.text;
    NSString *passWord = self.passwordTF.text;
    account = [account stringByReplacingOccurrencesOfString:@" " withString:@""];
    passWord = [passWord stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (account.length!=0&&passWord.length!=0) {
        //QMUITips *loadingTips = [[QMUITips alloc]initWithView:self.view];
        //[loadingTips showLoading];
        //[self.view addSubview:loadingTips];
        NSDictionary *parameters = @{@"ZH":account,@"PASSWORD":passWord};
        [[LMJRequestManager sharedManager] POST:[NSString stringWithFormat:@"%@/usercenter/login",url_base] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //[loadingTips hideAnimated:YES];
            if ([responseObject[@"errorcode"] isEqualToString:@"000000"]) {
                //登陆成功
                /**
                 存储登录获取到的cookie
                 */
                NSDictionary *fields = ((NSHTTPURLResponse*)task.response).allHeaderFields;
                [ [LMJRequestManager sharedManager].requestSerializer setValue:fields[@"Set-Cookie"] forHTTPHeaderField:@"Cookie"];
                /**
                 保存用户信息
                 */
                [[UserInfoModel sharedInstance] setValuesForKeysWithDictionary:responseObject[@"dataobj"]];
            
                [self dismissViewControllerAnimated:YES completion:nil];
                
                
            }else{
                //[ZSHelper showError:dataDict[@"value"][@"code"] inView:self.view hideAfterDelay:1.0f];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ZSHelper showLabelInWindowWithText:[error localizedDescription]];
        }];
        
    }else{
        //验证失败
        // *alertController = [QMUIAlertController alertControllerWithTitle:FGGetStringWithKeyFromTable(@"提示", nil) message:FGGetStringWithKeyFromTable(@"请输入正确的账号和密码",nil) preferredStyle:QMUIAlertControllerStyleAlert];
        //QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:FGGetStringWithKeyFromTable(@"确定", nil) style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
        //}];
        //[alertController addAction:action1];
        //[alertController showWithAnimated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            [ZSHelper showLabelInWindowWithText:@"请输入正确的账号和密码"];
        });
    }
}


/**
 注册
 */
- (void)registAction:(UIButton *)sender{
    
    [self hideKeyboard];
    ZSRegisterVC *registVC = [[ZSRegisterVC alloc] init];
    
    AiNavigationViewController *navi = [[AiNavigationViewController alloc] initWithRootViewController:registVC];
    
    [self presentViewController:navi animated:YES completion:nil];
}



/**
 忘记密码
 */
- (void)resetPasswordAction:(UIButton *)sender{
    
    [self hideKeyboard];
    ZSForgetPwdVC *forgetVC = [[ZSForgetPwdVC alloc] init];
    
    AiNavigationViewController *navi = [[AiNavigationViewController alloc] initWithRootViewController:forgetVC];
    
    [self presentViewController:navi animated:YES completion:nil];
}

#pragma mark - Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self hideKeyboard];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    [self hideKeyboard];
}
@end
